<template>
  <el-container>
    <el-main>
      <el-row class="table-wrapper">
        <el-col :span="24">
          <el-form :inline="true" label-width="80px">
            <el-form-item label="快递仓库">
              <el-select v-model="kkType" placeholder="快递仓库" clearable style="width: 195px;">
                <el-option
                  v-for="item in kktypes"
                  :key="item.kkId"
                  :label="item.kkDesc"
                  :value="item.kkType"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户名称">
              <el-input placeholder="用户名称" v-model="userName" style="width: 195px;" clearable></el-input>
            </el-form-item>
            <el-form-item label="快递单号">
              <el-input placeholder="快递单号" v-model="kkId" style="width: 195px;" clearable></el-input>
            </el-form-item>
            <el-form-item label="订单编号">
              <el-input placeholder="订单编号" v-model="outOrderId" style="width: 195px;" clearable></el-input>
            </el-form-item>
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="start"
                type="date"
                placeholder="开始日期"
                format="yyyyMMdd"
                value-format="yyyyMMdd"
                style="width: 195px;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="end"
                type="date"
                placeholder="结束日期"
                format="yyyyMMdd"
                value-format="yyyyMMdd"
                style="width: 195px;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="礼品列表">
              <el-select v-model="giftId" placeholder="礼品列表" clearable style="width: 195px;">
                <el-option
                  v-for="item in gifts"
                  :key="item.id"
                  :label="item.resourceDesc"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态">
              <el-select v-model="status" placeholder="订单状态" style="width: 195px;">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <el-button type="primary" @click="adminGetAllOrderDetail()">搜索</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="exportVisible = true">导出订单</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="startPrint()"
                    v-if="role === 'SUPER_ADMIN' || role === 'PRINTER'"
                  >全部打印</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="startBatchPrint()"
                    v-if="role === 'SUPER_ADMIN' || role === 'PRINTER'"
                    :disabled="selected"
                  >批量打印</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <el-dialog title="请选择导出格式" :visible.sync="exportVisible">
        <el-radio v-model="exportType" label="csv">.csv格式【适合wps打开】</el-radio>
        <el-radio v-model="exportType" label="excel">.xls格式【适合excel打开】</el-radio>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exportVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmExportType">确 定</el-button>
        </div>
      </el-dialog>
      <div class="table_container">
        <div class="Pagination" style="text-align: left;margin-top: 10px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 80, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
        <el-table
          :data="orderTableData"
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column property="outOrderId" label="订单编号" width="200"></el-table-column>
          <el-table-column property="userName" label="用户名称" width="130"></el-table-column>
          <el-table-column property="kkDesc" label="快递类型" width="150"></el-table-column>
          <el-table-column property="giftResourceDesc" label="礼物类型" width="130"></el-table-column>
          <el-table-column property="kkId" label="快递单号" width="150"></el-table-column>
          <el-table-column label="收货地址" width="300">
            <template
              slot-scope="scope"
            >{{ `${scope.row.receiverName}, ${scope.row.receiverTel}, ${scope.row.receiverAddress}`}}</template>
          </el-table-column>
          <el-table-column property="gmtCreate" label="下单时间" width="180"></el-table-column>
          <el-table-column label="发货地址" width="300">
            <template
              slot-scope="scope"
            >{{`${scope.row.name}; ${scope.row.tel}; ${scope.row.province} ${scope.row.city} ${scope.row.region} ${scope.row.detail}`}}</template>
          </el-table-column>
          <el-table-column label="备注信息" width="80">
            <template slot-scope="scope">{{ scope.row.memo === '' ? '空' : scope.row.memo }}</template>
          </el-table-column>
          <el-table-column label="订单状态">
            <template slot-scope="scope">{{ statusString(scope.row.status) }}</template>
          </el-table-column>
        </el-table>
        <div class="Pagination" style="text-align: left;margin-top: 10px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 80, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </el-main>

    <el-dialog
      title="打印中..."
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div>
        <span>{{this.printStatus}}</span>
      </div>
      <div v-if="printingData !== undefined">
        <span>{{`一共打印 ${printTotal}单 正在打印 第${currentPrint}单`}}</span>
      </div>
      <div
        v-if="printingData !== undefined"
      >当前打印：{{`${printingData.kkDesc} ${printingData.giftResourceDesc}`}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import {
  adminGetAllOrderDetail,
  fetchPrint,
  confirmPrint,
  adminExportAllOrderDetail
} from "@/api/admin";
import moment from "moment";
import { SUPER_ADMIN, PRINTER } from "@/utils/cookie";
// import {getExpressList} from '@/api/info'
// import {getGiftList} from '@/api/gift'
import csv from "csvtojson";
// import XLSX from 'xlsx'
import { mapState, mapGetters } from "vuex";

export default {
  data() {
    return {
      start: "",
      end: null,
      orderTableData: [],
      currentPage: 1,
      total: 0,
      limit: 20,
      socket: undefined,
      printHasNext: true,
      printPageSize: 50,
      // printPageIndex: 1,
      printStatus: "连接打印机成功",
      dialogVisible: false,
      printQueue: [],
      printingData: undefined,
      printFailedCount: 0,
      printTotal: 0,
      currentPrint: 0,
      statusOptions: [
        {
          value: "",
          label: "全部订单"
        },
        {
          value: "CREATE",
          label: "未支付"
        },
        {
          value: "ENABLE",
          label: "已支付"
        },
        {
          value: "TO_PRINT",
          label: "待打印"
        },
        {
          value: "FINISHED",
          label: "已打印"
        }
      ],

      kkType: "",
      giftId: "",
      userName: "",
      kkId: "",
      outOrderId: "",
      status: "",
      multipleSelection: [],
      isBatchPrint: false,
      exportType: "csv",
      exportVisible: false
    };
  },
  computed: {
    ...mapState(["role"]),
    ...mapGetters("manage", {
      gifts: "availableGifts",
      kktypes: "availableKKTypes"
    }),
    defaultActive: function() {
      return this.$route.path.replace("/", "");
    },
    selected: function() {
      return this.multipleSelection.length === 0;
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    async initData() {
      this.adminGetAllOrderDetail();
      // this.getExpressList()
      // this.getGiftList()
    },

    checkParam() {
      let params = {
        //   pageIndex: this.currentPage,
        //   pageSize: this.limit
        //   // status:"FINISH"
      };

      if (this.start != null && this.start.length !== 0) {
        params["start"] = this.start;
      }

      if (this.end !== null) {
        let endtime = moment(this.end);
        endtime.add(1, "d");
        params["end"] = endtime.format("YYYYMMDD");
      }

      if (this.status !== "") {
        params["status"] = this.status;
      }

      if (this.userName !== "") {
        params["userName"] = this.userName;
      }

      if (this.kkId !== "") {
        params["kkId"] = this.kkId;
      }

      if (this.kkType !== "") {
        params["kkType"] = this.kkType;
      }

      if (this.giftId !== "") {
        params["giftId"] = this.giftId;
      }
      if (this.outOrderId !== "") {
        params["outOrderId"] = this.outOrderId;
      }
      return params;
    },

    confirmExportType() {
      this.exportVisible = false;
      if (this.exportType === "excel") {
        this.exportAllOrderDetailToExcel();
      } else {
        this.exportAllOrderDetailToCSV();
      }
    },
    async exportAllOrderDetailToExcel() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        const params = {
          ...this.checkParam(),
          pageIndex: this.currentPage,
          pageSize: this.limit
        };
        let queryString = Object.keys(params)
          .map(key => {
            return (
              encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
            );
          })
          .join("&");
        const result = await adminExportAllOrderDetail(params);
        if (result.status === 200) {
          csv({
            // noheader:false,
            // output: "csv"
          })
            .fromString(result.data)
            .then(csvRow => {
              // let filterRows = []

              let filterRows = Object.assign(
                [],
                ...Object.keys(csvRow).map(k => {
                  let row = csvRow[k];
                  return {
                    [k]: Object.assign(
                      {},
                      ...Object.keys(row).map(e => {
                        let v = row[e];
                        return { [e]: v.substring(2, v.length - 1) };
                      })
                    )
                  };
                })
              );
              let wb = XLSX.utils.book_new();
              let ws = XLSX.utils.json_to_sheet(filterRows);
              // let time2 = (new Date()).format("yyyy-MM-dd")
              let time2 = moment().format("YYYY-MM-DD");
              XLSX.utils.book_append_sheet(wb, ws, "all");
              XLSX.writeFile(wb, `Export-${time2}.xls`);
            });
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        // this.$message.error('获取数据失败')
        console.log("获取数据失败", err);
      }
      loading.close();
    },
    async exportAllOrderDetailToCSV() {
      const params = {
        ...this.checkParam(),
        pageIndex: this.currentPage,
        pageSize: this.limit
      };
      let queryString = Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
          );
        })
        .join("&");
      window.open("/v01/user/order_detail/download/all" + "?" + queryString);
    },
    // async adminExportAllOrderDetail () {
    //   // try {
    //   const params = {
    //     ...this.checkParam(),
    //     pageIndex: this.currentPage,
    //     pageSize: this.limit
    //   }
    //   let queryString = Object.keys(params).map((key) => {
    //     return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
    //   }).join('&')
    //   window.open('/v01/user/order_detail/download/all' + '?' + queryString)
    //   // window.open(baseUrl + '?' + qs.stringify(params))
    //   //   const result = await adminExportAllOrderDetail(params)
    //   //   if (result.status === 200 && result.data.code === 200) {
    //   //     CsvExportor.downloadCsv(result.data, {header: true}, 'all_operater.csv')
    //   //   } else {
    //   //     throw new Error('获取数据失败')
    //   //   }
    //   // } catch (err) {
    //   //   // this.$message.error('获取数据失败')
    //   //   console.log('获取数据失败', err)
    //   // }
    // },
    async adminGetAllOrderDetail() {
      try {
        const params = {
          ...this.checkParam(),
          pageIndex: this.currentPage,
          pageSize: this.limit
        };
        const result = await adminGetAllOrderDetail(params);
        if (result.status === 200 && result.data.code === 200) {
          this.orderTableData = result.data.data;
          this.total = result.data.page.total;
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        // this.$message.error('获取数据失败')
        console.log("获取数据失败", err);
      }
    },

    handleSizeChange(size) {
      this.limit = size;
      this.adminGetAllOrderDetail();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.adminGetAllOrderDetail();
    },

    startPrint() {
      this.isBatchPrint = false;
      this.dialogVisible = true;
      this.printHasNext = true;
      // this.printPageIndex = 1
      this.printingData = undefined;
      this.printStatus = "连接打印机";
      this.printQueue = [];
      this.doConnect();
    },

    startBatchPrint() {
      this.isBatchPrint = true;
      this.dialogVisible = true;
      this.printHasNext = true;
      // this.printPageIndex = 1
      this.printingData = undefined;
      this.printStatus = "连接打印机";
      this.printQueue = this.multipleSelection;
      this.doConnect();
    },
    handleClose() {
      this.dialogVisible = false;
      this.socket.close();
      this.printQueue = [];
    },

    printFinishHandler(response) {
      if (response.taskStatus !== "failed") {
        if (response.printStatus[0].status === "success") {
          this.confirmPrint();
          this.printNext();
        } else {
          this.printFailedCount += 1;
          this.printNext();
        }
      } else {
        this.printFailedCount += 1;
        this.printNext();
      }
    },

    async confirmPrint() {
      try {
        const result = await confirmPrint({
          id: this.printingData.id
        });
        if (result.status === 200 && result.data.code === 200) {
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        console.log("confirm failed", err);
      }
    },
    async fetchPrint() {
      this.printStatus = "正在拉取打印列表";
      try {
        const params = {
          ...this.checkParam(),
          pageIndex: 1,
          pageSize: this.printPageSize
        };
        const result = await fetchPrint(params);
        if (result.status === 200 && result.data.code === 200) {
          this.printQueue = result.data.data;
          this.printHasNext = this.printQueue.length === this.printPageSize;
          this.printStatus = "获取打印列表完成";

          this.printTotal = this.printTotal + this.printQueue.length;

          this.printNext();
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        this.dialogVisible = false;
        console.log("获取数据失败", err);
      }
    },

    printNext() {
      if (this.printQueue.length === 0) {
        if (!this.printHasNext) {
          this.finishPrint();
        } else {
          // this.printPageIndex += 1
          this.printQueue = [];
          this.fetchPrint();
        }
      } else {
        this.currentPrint = this.currentPrint + 1;
        this.printingData = this.printQueue.shift();
        this.printStatus = "正在打印";
        let cainiao = JSON.parse(this.printingData.kkResponse);
        let document = JSON.parse(
          cainiao.cainiao_waybill_ii_get_response.modules
            .waybill_cloud_print_response[0].print_data
        );
        // let document = {'data': {'cpCode': 'STO', 'needEncrypt': false, 'packageInfo': {'items': [{'count': 1, 'name': '景观石'}], 'volume': 0, 'weight': 1}, 'parent': false, 'recipient': {'address': {'detail': '海南三亚市吉阳区吉阳镇荔枝沟村三巷蓓蕾幼儿园旁', 'province': '海南'}, 'mobile': '13691642469', 'name': '林桂香'}, 'routingInfo': {'consolidation': {'name': '三亚中转包'}, 'origin': {'code': '362700', 'name': '福建石狮公司'}, 'receiveBranch': {'code': '572052'}, 'routeCode': 'G01 B08', 'sortation': {'name': '682'}, 'startCenter': {}, 'terminalCenter': {}}, 'sender': {'address': {'city': '泉州市', 'detail': '陶城东路523号', 'district': '石狮市', 'province': '福建省'}, 'mobile': '18905812648', 'name': '吴荣耀'}, 'shippingOption': {'code': 'STANDARD_EXPRESS', 'title': '标准快递'}, 'waybillCode': '3370473943279'}, 'signature': 'MD:AwrrxFK6YcAZsre/rAUY6Q\u003d\u003d', 'templateURL': 'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=201&version=4'}
        this.doPrint("", false, document, this.printingData);
      }
    },

    finishPrint() {
      this.dialogVisible = false;

      this.$message({
        type: "info",
        message: `打印完成, 其中打印失败${this.printFailedCount}份}`
      });
    },
    doConnect() {
      this.socket = new WebSocket("ws://localhost:13528");
      // 如果是https的话，端口是13529
      // socket = new WebSocket('wss://localhost:13529');
      // 打开Socket
      this.socket.onopen = event => {
        // 监听消息
        console.log("web socket connect success", event);
        if (this.isBatchPrint) {
          this.printHasNext = false;
          this.printStatus = "获取打印列表完成";
          this.printTotal = this.printQueue.length;
          this.currentPrint = 0;
          this.printNext();
        } else {
          this.printTotal = 0;
          this.currentPrint = 0;
          this.fetchPrint();
        }

        this.socket.onmessage = event => {
          console.log("Client received a message", event);
          let response = JSON.parse(event.data);
          if (response.cmd === "notifyPrintResult") {
            this.printFinishHandler(response); // 处理打印机列表
          } else if (response.cmd === "print") {
            console.log(response);
          }
        };
        // 监听Socket的关闭
        this.socket.onclose = event => {
          console.log("Client notified socket has closed", event);
        };
      };
    },
    /***
     *
     * 获取请求的UUID，指定长度和进制,如
     * getUUID(8, 2)   //"01001010" 8 character (base=2)
     * getUUID(8, 10) // "47473046" 8 character ID (base=10)
     * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
     *
     */
    getUUID(len, radix) {
      let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      let uuid = [];
      let i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
    /***
     * 构造request对象
     */
    getRequestObject(cmd) {
      let request = {};
      request.requestID = this.getUUID(8, 16);
      request.version = "1.0";
      request.cmd = cmd;
      return request;
    },

    /***
     * 获取自定义区数据以及模板URL
     * waybillNO 电子面单号
     */
    // getCustomAreaData (waybillNO) {
    //   // 获取waybill对应的自定义区的JSON object，此处的ajaxGet函数是伪代码
    //   let jsonObject = {} // ajaxGet(waybillNO)
    //   let ret = {}
    //   ret.templateURL = jsonObject.content.templateURL
    //   ret.data = jsonObject.content.data
    //   return ret
    // },
    /***
     * 获取电子面单Json 数据
     * waybillNO 电子面单号
     */
    // getWaybillJson (waybillNO) {
    // 获取waybill对应的json object，此处的ajaxGet函数是伪代码
    // let jsonObject = {} // ajaxGet(waybillNO)
    // return jsonObject
    // },

    /**
     * 打印电子面单
     * printer 指定要使用那台打印机
     * waybillArray 要打印的电子面单的数组
     */
    doPrint(printer, preview, printData, order) {
      let request = this.getRequestObject("print");
      request.task = {};
      request.task.taskID = this.getUUID(8, 10);
      request.task.preview = preview;
      request.task.printer = printer;
      request.task.previewType = "pdf";
      request.task.notifyType = ["print"];
      let documents = [];
      let doc = {};
      doc.documentID = this.getUUID(8, 10);
      let contents = [];
      let waybillJson = Object.assign({}, printData);
      if (order.city === "泉州市") {
        // let items = order.address.trim().split(/;/)
        // let address = items[2]
        // let addressComponets = address.trim().split(/\s+/)
        waybillJson.data.sender = {
          address: {
            city: order.city,
            detail: order.detail,
            district: order.region,
            province: order.province
          },
          mobile: order.tel,
          name: order.name
        };
      } else {
        // let items = order.address.trim().split(/;/)
        waybillJson.data.sender.mobile = order.tel;
        waybillJson.data.sender.name = order.name;
      }

      let customAreaData = {}; // this.getCustomAreaData(waybillArray[i])
      customAreaData.templateURL =
        "http://cloudprint.cainiao.com/template/customArea/6575944";
      customAreaData.data = {
        deliver_content:
          order.memo === ""
            ? printData.data.packageInfo.items[0].name
            : order.memo
      };
      //
      contents.push(waybillJson, customAreaData);
      doc.contents = contents;
      documents.push(doc);
      request.task.documents = documents;
      this.socket.send(JSON.stringify(request));
    },

    statusString(status) {
      switch (status) {
        case "CREATE":
          return "未支付";
        case "ENABLE":
          return "已支付";
        case "TO_PRINT":
          return "待打印";
        case "FINISHED":
          return "已打印";
        default:
          return "已取消";
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../style/mixin";
.table-wrapper {
  border: 1px solid #ebeef5;
  margin: 30px 0;
  padding-top: 20px;
  padding-left: 10px;
}

.label-title {
  font-weight: bold;
  font-size: 24px;
  color: #ff633b;
  margin: 30px;
}
.introduct {
  width: 900px;
  text-align: center;
  margin: auto;
}
// .el-button {
//   width: 200px;
//   margin: auto;
//   display: block;
// }
.el-table .info-row {
  background: #c9e5f5;
}

.el-table .positive-row {
  background: #e2f0e4;
}
</style>
